/**
	Copyright (c) 2009 Ozazo Pvt Ltd, INDIA

	Permission is hereby granted, free of charge, to any person or organization 
	obtaining a copy of this software and associated  documentation  files (the 
	"Software"), to deal in the Software without restriction, including without 
	limitation the rights to use, copy, modify, merge, publish, distribute, sub
	license, and/or sell copies of the Software, and to permit persons  to whom 
	the Software is furnished to do so, subject to the following conditions:
	
	The above copyright notice and  this permission notice shall be included in 
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS",  WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING  BUT NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY,  WHETHER  IN  AN  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
	FROM,  OUT  OF  OR  IN  CONNECTION  WITH  THE  SOFTWARE OR THE USE OR OTHER 
	DEALINGS IN THE SOFTWARE.
 */

package com.ozazo.wave.robots.servlets;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

import javax.servlet.http.HttpSession;

import com.google.wave.api.*;
import com.ozazo.wave.robots.engines.BlipDataParser;
import com.ozazo.wave.robots.fw.engines.RobotContainer;
import com.ozazo.wave.robots.fw.engines.RobotContainerInterface;
import com.ozazo.wave.robots.fw.engines.RobotContainerFactory;

/**
 * 
 * @author:	 Araf Karsh Hamid
 * @version: 1.0
 * @serial:	 20091121102030
 */

@SuppressWarnings("serial")
public class OzroboServlet extends AbstractRobotServlet {
	private static final Logger log = Logger.getLogger(OzroboServlet.class.getName());
	
	public void init() {
		// super.init();
		String configFile = this.getServletConfig().getInitParameter("botConfig");
		String rPath = this.getServletContext().getRealPath(configFile);
		System.out.println("Config File = "+rPath);
		// log.severe("Setting Config File Name = "+rPath + " in the system property.");
		if(configFile != null) {
			System.setProperty("botConfig", rPath);
		}
		RobotContainerInterface bot = RobotContainerFactory.getInstance().getRobotContainer();		
	}
	
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
	    
		if (bundle.wasSelfAdded()) {
	    	botSelfAdded(wavelet);						// Action when you add the Robot
	    } else if (bundle.wasSelfRemoved()) {
	    	botSelfRemoved(wavelet);					// Action when you remove the Robot
	    } else {       
	    	for (Event e: bundle.getEvents()) {
	    		switch (e.getType()) {
	    			case WAVELET_PARTICIPANTS_CHANGED:
	    				onWaveletParticipantsChanged(e);
	    				break;
	    			case BLIP_SUBMITTED:
	    				log.info("Log - BLIP submitted.");
	    				onBlipSubmitted(e);
	    				break;
	    			case DOCUMENT_CHANGED:
	    				onDocumentChanged(e);
	    				break;
	    		}	// end of switch
	    	}	// end of for loop
	    }	// end of else statement 
	}	// end of processEvents() method call

	/**
	 * Appending Intro Blip when the Robot is added to a wave.
	 * 
	 * @param wavelet
	 */
	
	private void botSelfAdded(Wavelet wavelet) {
    	Blip blip = wavelet.appendBlip();
    	TextView textView = blip.getDocument();
    	textView.replace(TITLE + VERSION + ". Commands\n"
    			+ "/w   Kerala : to hyper link a word to Wikipedia.\n"
    			+ "/w  \"Quantum Physics\" OR /w 'EPR Paradox'\n"
    			+ "/wd  India : to get the Wikipedia description.\n"
    			+ "/ltx for LateX commands. "
    			+ "More examples: http://ozobuddyrobo.appspot.com/ ");		
    	// HttpSession session = request.getSession(true);
	}

	/**
	 * Adding sign out message to the wave.
	 * 
	 * @param wavelet
	 */
	private void botSelfRemoved(Wavelet wavelet) {
	    // Action when the Robot is removed
    	Blip blip = wavelet.appendBlip();
    	TextView textView = blip.getDocument();
    	textView.append(TITLE + VERSION +
    			" signing out. Have a nice time folks.");	    			
	}

	/**
	 * Doing nothing if the participants changed.
	 * @param e
	 */
	
	private void onWaveletParticipantsChanged(Event e) {
		return;
	}
	
	/**
	 * Calling the Engines on DOCUMENT_CHANGED Event. This (real-time updates) can be stopped 
	 * by having the command '!.' in the beginning of the blip.
	 *
	 * @param Event e
	 */
	
	private void onDocumentChanged(Event e) {
		Blip blip = e.getBlip();
		String txt = blip.getDocument().getText();
		if(txt != null && !txt.startsWith(TITLE) && !txt.startsWith(SIGMA) && txt.length() > 3) {
			// RobotContainer bot = new RobotContainer(log);
			RobotContainerInterface bot = RobotContainerFactory.getInstance().getRobotContainer();
			bot.setRealTime(true);
			bot.processBlip(blip);
		}
	}
	
	/**
	 * Calling the Engine(s) when the Blip is submitted.
	 * 
	 * @param Event e
	 */
	private void onBlipSubmitted(Event e) {
		Blip blip = e.getBlip();
		String txt = blip.getDocument().getText();
		if(txt != null && !txt.startsWith(TITLE)) {
			// RobotContainer bot = new RobotContainer(log);
			RobotContainerInterface bot = RobotContainerFactory.getInstance().getRobotContainer();
			bot.processBlip(blip);
		}
	}

	// private static final String DEV		= "TESTING VERSION ";
	// private static final String VERSION = "v022";

	private static final String DEV		= "";
	private static final String VERSION = "v02";

	private static final String TITLE	= "\nOzazo Buddy Robot " + DEV;
	private static final String SIGMA	= "!.";

}
